package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {

    /**
     * 登录业务
     *
     * @param dto
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.参数校验
        if(dto == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //判断为登录用户还是游客
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //2.登录用户：根据用户名查询用户消息并验证
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(user == null)
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在！！");

            //2.1加盐验证密码
            String passwordByDigest = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
            if(!passwordByDigest.equals(user.getPassword()))
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误！！");

            //2.2验证通过返回用户消息和token
            Map users = new HashMap();
            users.put("name",user.getName());
            users.put("phone",user.getPhone());

            Map map = new HashMap();
            map.put("user",users);
            map.put("token", AppJwtUtil.getToken(Long.valueOf(user.getId())));
            return ResponseResult.okResult(map);
        }else {
            //3.游客：直接生成token
            Map map = new HashMap();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }


}
